package com.sike.netty.im.server.handler;

import cn.hutool.json.JSONUtil;
import com.sike.netty.im.common.command.CommandBody;
import com.sike.netty.im.common.command.LoginResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.common.enums.ResponseStatusEnum;
import com.sike.netty.im.server.util.LoginUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 鉴权 handler
 *
 * @author chenssy
 * @date 2023/09/17
 */
@Slf4j
public class AuthHandler extends SimpleChannelInboundHandler<CommandBody> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CommandBody msg) throws Exception {
        log.info("当前连接[{}]进入鉴权逻辑，message:{}",ctx.channel(), JSONUtil.toJsonStr(msg));

        if (!LoginUtil.hasLogin(ctx.channel())) {
            LoginResponseCommand loginResponseCommand = new LoginResponseCommand();
            loginResponseCommand.setRetCode(ResponseStatusEnum.FAILURE.getCode());
            loginResponseCommand.setRetMessage("您还没有登录，请先登录");
            Message message = MessageBuilder.buildMessage(loginResponseCommand,null,null);

            ctx.channel().writeAndFlush(message);
        } else {
            // 鉴权通过删除该 Channel
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("当前连接{}登录鉴权已通过，无须再次验证，AuthHandler 已被移除",ctx.channel());
    }
}
